package cn.swust.designpatternlearningplatform.controller;

import cn.swust.designpatternlearningplatform.common.Result.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@RestController
@RequestMapping("/upload")
public class FileUpload {
    @Value("${upload_path}")
    public String uploadPath;
    /**
    	 * @param avatar:
    	 * @param request:
      * @return FilePathBo
     * @author wang
     * description 学生上传头像的方法
     * date 2023/5/21 20:48
     */
    @RequestMapping("/setFilePath")
    public R<Object> setFilePath(@RequestBody MultipartFile avatar, HttpServletRequest request) throws IOException {
        if (avatar == null || avatar.isEmpty()) {
            return R.error("未上传图片");
        }
        else {
            //上传的为学生的头像
            String uuid = UUID.randomUUID().toString();
            String newFileName = uuid + ".jpg";
            String localPath = uploadPath + newFileName;
            System.out.println(newFileName);
            System.out.println(localPath);
            //前端可以 通过这个路径直接访问
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +"/images/" + newFileName;
            //log.info("上传的网络地址为：{}", url);
            //将文件上传在对应的服务器文件夹下面
            File file=new File(localPath);
            avatar.transferTo(file);
            return R.success((Object) url);
        }
    }
}
